package com.n9.echo.test;


import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author ice
 * @since 2019/1/31 17:16
 */
public class EchoServer {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Test
    public void start() throws Exception {
        ServerSocketChannel sc = ServerSocketChannel.open();
        sc.bind(new InetSocketAddress("localhost", 19999));

        while(true) {
            final SocketChannel accept = sc.accept();
            final ByteBuffer buf = ByteBuffer.allocate(2048);
            new Thread(()->{
                while(true) {
                    try {
                        int len = accept.read(buf);
                        if (len > 0) {
                            byte[] data = new byte[len];
                            buf.flip();
                            buf.get(data);

                            String receiveMsg = new String(data);
                            log.info("receive:{}", receiveMsg);

                            buf.clear();
                            receiveMsg = "echo response:" + receiveMsg;
                            buf.put(receiveMsg.getBytes());
                            buf.flip();
                            accept.write(buf);
                            buf.clear();
                        } else if(len == -1) {
                            break;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        break;
                    }
                }

                try {
                    accept.close();
                } catch (Exception e) {
                }

                log.info("客户端断开连接");
            }).start();
        }
    }

}
